package com.mingmen.supplier.activity;


import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mingmen.supplier.R;
import com.mingmen.supplier.base.BaseBean;
import com.mingmen.supplier.defineview.ClearEditText;
import com.mingmen.supplier.http.callback.StringCallback;
import com.mingmen.supplier.httpconfig.HttpResponse;
import com.mingmen.supplier.immersionbar.ImmersionBar;
import com.mingmen.supplier.model.LoginBean;
import com.mingmen.supplier.model.LoginModel;
import com.mingmen.supplier.model.LoginReturnBean;
import com.mingmen.supplier.tabuse.ui.SimpleHomeActivity;
import com.mingmen.supplier.util.DESUtil;
import com.mingmen.supplier.util.GsonUtil;
import com.mingmen.supplier.util.Mobile;
import com.mingmen.supplier.util.SharePreferenceUtil;
import com.mingmen.supplier.util.ToastUtil;


import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import de.greenrobot.event.EventBus;
import okhttp3.Call;
import okhttp3.Response;

public class LoginActivity extends AppCompatActivity {

    //登录按钮
    @BindView(R.id.btn_login)
    Button btnLogin;


    @BindView(R.id.edit_Phone)
    ClearEditText editPhone;
    @BindView(R.id.edit_Passwrord)
    ClearEditText editPasswrord;

    @BindView(R.id.text_forget)
    TextView textForget;
    @BindView(R.id.text_register)
    TextView textRegister;
    @BindView(R.id.tv_login)
    TextView tvLogin;
    //    密码可见
    @BindView(R.id.img_open)
    ImageView imgOpen;
    //    密码不可见
    @BindView(R.id.img_close)
    ImageView imgClose;
    @BindView(R.id.img_logo)
    ImageView imgLogo;

    String companyId;
    private int resurtResurant = 100;
    @BindView(R.id.layout_img)
    LinearLayout layout_img;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .init();

        companyId = (String) SharePreferenceUtil.get(this, "companyId", "");
        imgLogo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                startActivity(new Intent(LoginActivity.this, FilterNewLoginListActivity.class));
//                startActivity(new Intent(LoginActivity.this, ZhenBanReplaceFragmentActivity.class));
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.putExtra("logindata", "727372723");
                startActivityForResult(intent, resurtResurant);
            }
        });
        tvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(LoginActivity.this, SimpleHomeActivity.class));

            }
        });

        //待加密内容
        String str = "测试内容";
        //密码，长度要是8的倍数
        String password = "mingmenkeji";

        byte[] result = DESUtil.encrypt(str.getBytes(), password);
        System.out.println("加密后：" + new String(result));
        //直接将如上内容解密
        try {
            byte[] decryResult = DESUtil.decrypt(result, password);
            System.out.println("解密后：" + new String(decryResult));
        } catch (Exception e1) {
            e1.printStackTrace();
        }

        editPasswrord.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                imgClose.setVisibility(View.GONE);
                imgOpen.setVisibility(View.GONE);

                if (editPasswrord.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
                    imgClose.setVisibility(View.VISIBLE);

                    imgOpen.setVisibility(View.GONE);
                } else {
                    imgClose.setVisibility(View.GONE);
                    imgOpen.setVisibility(View.VISIBLE);
                }
                return false;
            }
        });
        layout_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("layout_img", "layout_img");
                if (flag == 0) {
                    //密码明文显示
                    editPasswrord.setTransformationMethod(PasswordTransformationMethod.getInstance());
                    imgClose.setVisibility(View.VISIBLE);
                    imgOpen.setVisibility(View.GONE);
                    editPasswrord.setSelection(editPasswrord.length());
                    flag = 1;
                } else {
                    editPasswrord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                    imgClose.setVisibility(View.GONE);
                    imgOpen.setVisibility(View.VISIBLE);
                    editPasswrord.setSelection(editPasswrord.length());
                    flag = 0;
                }

            }
        });
        editPhone.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                imgClose.setVisibility(View.GONE);
                imgOpen.setVisibility(View.GONE);

                return false;
            }
        });
    }

    int flag = 0;

    //, R.id.img_close, R.id.img_open
    @OnClick({R.id.edit_Phone, R.id.edit_Passwrord, R.id.btn_login, R.id.text_forget, R.id.text_register})
    public void onViewClicked(View view) {
        if (isFastClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.btn_login:
//                对登录条件进行判断
//                startActivity(new Intent(LoginActivity.this, MainActivity.class));


                if (TextUtils.isEmpty(editPhone.getText().toString())) {
                    ToastUtil.showToast(LoginActivity.this, "手机号不能为空");
                } else if (!Mobile.isMobile(editPhone.getText().toString())) {
                    ToastUtil.showToast(LoginActivity.this, "请输入正确手机号");
                } else if (TextUtils.isEmpty(editPasswrord.getText().toString())) {
                    ToastUtil.showToast(LoginActivity.this, "密码不能为空");
                } else {
//                    ToastUtil.showToast(LoginActivity.this, "登录");
                    if (!isnetwork(this)) {
                        Toast.makeText(this, "当前无网络", Toast.LENGTH_SHORT).show();
                    } else {
                        getLogin();
                    }

                }

                break;
            case R.id.text_forget:
                startActivity(new Intent(LoginActivity.this, ForgetActivity.class));
                break;
            case R.id.text_register:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;
            case R.id.layout_img:
                break;
         /*   case R.id.img_open:
                //密码明文显示
                editPasswrord.setTransformationMethod(PasswordTransformationMethod.getInstance());
                imgClose.setVisibility(View.VISIBLE);
                imgOpen.setVisibility(View.GONE);
                editPasswrord.setSelection(editPasswrord.length());
                flag = 1;
                break;
            case R.id.img_close:
                editPasswrord.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                imgClose.setVisibility(View.GONE);
                imgOpen.setVisibility(View.VISIBLE);
                editPasswrord.setSelection(editPasswrord.length());
                flag = 0;
                break;*/

        }
    }

    private static final int MIN_DELAY_TIME = 1000;  // 两次点击间隔不能少于1000ms
    private static long lastClickTime;

    public static boolean isFastClick() {
        boolean flag = true;
        long currentClickTime = System.currentTimeMillis();
        if ((currentClickTime - lastClickTime) >= MIN_DELAY_TIME) {
            flag = false;
        }
        lastClickTime = currentClickTime;
        return flag;
    }

    public void getLogin() {
        if (companyId.isEmpty()) {
            companyId = "0";
        } else {
            {

            }
        }
        HttpResponse.getLogin(editPhone.getText().toString(), editPasswrord.getText().toString(), "2", "0", "2", new StringCallback(LoginActivity.this) {
            @Override
            public void onSuccess(String s, Call call, Response response) {
//501 502
                Log.d("login", s);
                BaseBean baseBean = GsonUtil.GsonToBean(s, BaseBean.class);
                if (baseBean.getCode() == 0) {
//                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    LoginModel loginModel = new LoginModel();
                    loginModel = GsonUtil.GsonToBean(s, LoginModel.class);

                    SharePreferenceUtil.put(LoginActivity.this, "token", loginModel.getData().getToken());

                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    Toast.makeText(LoginActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();


                } else if (baseBean.getCode() == 501 || baseBean.getCode() == 502) {
                    Intent intent = new Intent(LoginActivity.this, LoginShenHeActivity.class);
                    intent.putExtra("logindata", s);
//                    startActivityForResult(intent, resurtResurant);
                    startActivity(intent);
                } else {

                }
                Toast.makeText(LoginActivity.this, baseBean.getMessage() + "", Toast.LENGTH_SHORT).show();

            }
        });

    }


    String token;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == resurtResurant) {

            companyId = data.getStringExtra("companyId");
            token = data.getStringExtra("token");
            SharePreferenceUtil.put(LoginActivity.this, "companyId", companyId);
            SharePreferenceUtil.put(LoginActivity.this, "token", token);

            Log.d("loginactivity", token);
        }
    }


    public void onEventMainThread(Integer integer) {
        if (integer == 11) {
            String phone = (String) SharePreferenceUtil.get(LoginActivity.this, "phone", "");
            String pwd = (String) SharePreferenceUtil.get(LoginActivity.this, "pwd", "");
            editPhone.setText(phone);
            editPasswrord.setText(pwd);
        }
    }

    public boolean isnetwork(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null) {
            return activeNetworkInfo.isAvailable();
        }
        return false;
    }
}




